package stock.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import stock.mapper.StockMapper;
import stock.pojo.SecKillGoods;

@Service
public class StockService {
    @Autowired
    StockMapper stockMapper;

    @Transactional
    public boolean updateStock(SecKillGoods secKillGoods) {

        return stockMapper.updateSecGoods(secKillGoods);
    }
    @Transactional(rollbackFor = Exception.class)
    public String deduct(SecKillGoods secKillGoods) {
        SecKillGoods secKillGoods1 = stockMapper.querySecGoods(secKillGoods);
        if (secKillGoods1 == null) {
            return "查詢爲空";
        }
        Long sum = secKillGoods1.getSum() - secKillGoods.getSum();
        if (sum < 0) {
            return "庫存不足";
        }
        secKillGoods1.setExpectedSum(secKillGoods1.getSum());//将未设置的值设为预期值  希望他没有被改变 乐观锁
        secKillGoods1.setSum(sum);//将修改后的值设为即将修改的值
        boolean b = updateStock(secKillGoods1);
        if (!b) {
            return "發生錯誤";
        }
        return "操作成功";
    }
}
